﻿using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Helper;
using Transformable_Engine_v2.Engine.Transformable_Math.Geometry;

namespace Super_Management_Mayhem.Screens.Playing.Players
{
    public partial class Manager
    {
        void HandleMovement(TE_Vector2 movementOffset, bool applyMovement = true)
        {
            MoveAndHandleCollision(movementOffset, applyMovement);
            var hasWarped = HandleWarpCollision();
            CalculateCameraPosition(hasWarped);
            CollectPoints();
        }

        void CollectPoints()
        {
            if (_currentPlayerState != PlayerState.Hurt)
            {
                foreach (var point in Playscreen.Map.GetPoints())
                {
                    if (CollisionHelper.Intersects(_boundingBox + _player.Position, point.GetBoundingBox()))
                    {
                        _statistics.CollectPoint(point.Value);
                        point.Collect();
                    }
                }
            }
        }

        void MoveAndHandleCollision(TE_Vector2 movementOffset, bool applyMovement)
        {
            TE_Rectangle oldBounding;
            TE_Rectangle newBounding;
            if(applyMovement) {
                oldBounding = new TE_Rectangle(_player.Position + _boundingBox.Position, _boundingBox.Size);
                newBounding = new TE_Rectangle(_player.Position + movementOffset + _boundingBox.Position, _boundingBox.Size);
            } 
            else 
            {
                oldBounding = new TE_Rectangle(_player.OldPosition + _boundingBox.Position, _boundingBox.Size);
                newBounding = new TE_Rectangle(_player.Position + _boundingBox.Position, _boundingBox.Size);
            }
            TE_Vector2 velocity = newBounding.Position - oldBounding.Position;
            TE_Vector2 normal;
            var collisionOffset = Playscreen.Map.ResolveCollision(oldBounding, newBounding, velocity, out normal);

            if (collisionOffset == null)
            {
                _player.Position = newBounding.Position - _boundingBox.Position;
            }
            else
            {
                //Set it twice, so we don't have an invalid oldPosition
                _player.Position = collisionOffset - _boundingBox.Position;
                //_player.Position = collisionOffset - _boundingBox.Position;
            }
        }

        bool HandleWarpCollision()
        {
            foreach (var warp in Playscreen.Map.GetWarp())
            {
                if (CollisionHelper.Intersects(warp.BoundingBox, _player.Position))
                {
                    _player.Position = warp.WarpPlayer().Offset(8, 8);
                    return true;
                }
            }

            return false;
        }
    }
}